﻿using Spine;
using Spine.Unity;
using Spine.Unity.AttachmentTools;
using UnityEngine;

public abstract class PersonBase : MonoBehaviour
{
    public SpineAtlasAsset AtlasAsset;

    public SkeletonGraphic skeletonGraphic;
    
    protected EquipmentBase myEquipment;
    public EquipmentBase Equipment => myEquipment;
    protected abstract void OnEnterAnim();
    protected abstract void PlaySound();

    public void AddEquipment(EquipmentBase equipment)
    {
        this.myEquipment = equipment;
        RefreshEquipment();
    }

    public void RefreshEquipment()
    {
        skeletonGraphic.allowMultipleCanvasRenderers = true;
        ChangeSlot(AtlasAsset.GetAtlas().FindRegion(myEquipment.EquipName));
    }

    private void AddIdleAnim()
    {
        skeletonGraphic.AnimationState.AddAnimation(0, "wait",true,0);
    }
   
    public void ShowPreView()
    {
        OnEnterAnim();
        PlaySound();
        myEquipment?.ShowPreView();
        AddIdleAnim();
    }
    
    /// <summary>
    /// 替换Spine的Attachment
    /// </summary>
    public void ChangeSlot(AtlasRegion atlasRegion)
    {
        Slot slot = skeletonGraphic.Skeleton.FindSlot(myEquipment.SlotName);
        if (atlasRegion == null)
        {
            return;
        }
        
        if (slot != null)
        {
            if (slot.Attachment is MeshAttachment)
            {
                MeshAttachment originAct = slot.Attachment as MeshAttachment;
                originAct.RegionDegrees =  atlasRegion.degrees;
                MeshAttachment atc = originAct.GetRemappedClone(atlasRegion,true,true) as MeshAttachment;
                
                slot.Attachment = atc;
            }
            else if (slot.Attachment is  RegionAttachment)
            {
                RegionAttachment originAct = slot.Attachment as RegionAttachment;
                //originAct.Rotation = atlasRegion.degrees;
                RegionAttachment atc = originAct.GetRemappedClone(atlasRegion,true,true) as RegionAttachment;

                slot.Attachment = atc;
            }
            else if (slot.Attachment == null)
            {
                return;
            }
            else
            {
                return;
            }
            
            //SetSpine(GameUtils.GetAnimeNameMapping(m_spine.SkeletonDataAsset.name, AnimeMappingType.Win), true);
            skeletonGraphic.Update(0);
            skeletonGraphic.LateUpdate();
        }
    }
}
